import os
import numpy as np
from PIL import Image
from scipy.ndimage import label

INPUT = "../input/atlas/texture_atlas.png"
OUTPUT = "../output/atlas"

def split_atlas_advanced(atlas_path, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    atlas = Image.open(atlas_path).convert('RGBA')
    data = np.array(atlas)
    alpha = data[:, :, 3]
    
    # 二值化：非透明=1, 透明=0
    binary = (alpha > 0).astype(int)
    
    # 标记连通区域
    labeled, num_features = label(binary)
    
    for i in range(1, num_features + 1):
        # 获取当前小图的像素坐标
        coords = np.where(labeled == i)
        min_y, max_y = np.min(coords[0]), np.max(coords[0])
        min_x, max_x = np.min(coords[1]), np.max(coords[1])
        
        # 切割并保存
        sub_img = atlas.crop((min_x, min_y, max_x + 1, max_y + 1))
        sub_img.save(os.path.join(output_dir, f"sprite_{i}.png"))
        print(f"保存: sprite_{i}.png")

if __name__ == "__main__":
    split_atlas_advanced(INPUT, OUTPUT)